import { mountStoreDevtool } from 'simple-zustand-devtools';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export type routerStoreItem = { label: string; key: string };

interface RouterStore {
  routers: routerStoreItem[];
  activeKey: string;
  pushRouter: (item: routerStoreItem) => void;
  deleteRouter: (index: number) => void;
  jumpRouter: (index: number) => routerStoreItem;
  setLocalRouter: () => void;
}

let store = (set, get) => ({
  routers: [],
  activeKey: '0',
  // 添加路由
  pushRouter: (item: routerStoreItem) => {
    const router = get().routers;
    if (!router.length) {
      set((state) => ({ routers: [...state.routers, item], activeKey: '0' }));
      // localStorage.setItem('router', JSON.stringify([item]));
    } else {
      if (router.every((e) => e.key !== item.key)) {
        set((state) => ({ routers: [...state.routers, item], activeKey: (state.routers.length - 1).toString() }));
        // localStorage.setItem('router', JSON.stringify(get().routers));
        return;
      }
      const index = router.filter((f) => f.key === item.key);
      set({ activeKey: index[0].key });
    }
  },

  // 删除路由
  deleteRouter: (index: number) => {
    const routers = get().routers;
    routers.splice(index, 1);
    // localStorage.setItem('router', JSON.stringify(get().routers));
    set((state) => ({ routers: [...routers] }));
  },

  // 跳转
  jumpRouter: (index: number) => {
    const routers = get().routers;
    set({ activeKey: index.toString() });
    return routers[index];
  },

  // 页面加载
  setLocalRouter: () => {
    set({ activeKey: get().activeKey });
  },
});

store = persist(store, { name: 'useRouterStore' });

const useRouterStore = create<RouterStore>(store);

mountStoreDevtool('useRouterStore', useRouterStore);

export default useRouterStore;
